import { DeviceEventEmitter } from "react-native";
import axios from "axios";
import TokenStorage from "./TokenStorage";
import { UserDidSigninedNotification } from "../base/constants";

const showLogin = () => {
    DeviceEventEmitter.emit("showLogin");
};

const login = (data) => {
    return new Promise((resolve, reject) => {
        axios.post("https://shop.gzdsx.cn/oauth/token", {
            "grant_type": "password",
            "client_id": "2",
            "client_secret": "RIBklHvmIpQAje6RYw9Pd7r8HkAPnj5jkPWswCiK",
            "scope": "*",
            ...data,
        }).then(response => {
            //console.log(response.data);
            const { access_token } = response.data;
            if (access_token) {
                TokenStorage.updateToken(access_token).then(() => {
                    DeviceEventEmitter.emit(UserDidSigninedNotification);
                    resolve(response.data);
                });
            } else {
                reject(response.data);
            }
        }).catch(reason => {
            reject(reason);
        });
    });
};

export default {
    showLogin,
    login,
};
